package huzh.foundation.appserver;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import javax.transaction.UserTransaction;

/**
 *<p>title:WeblogicUtil</p>
 *<p>description:</p>
 * @since 2014-6-8
 * @author huzh
 * @version 1.0
 */
public class WeblogicUtil extends AbstractAppServerService {

    /**WLS*/
    public static final String WLS = "weblogic";
    /**WLS_JNDI_FACTORY*/
    public static final String WLS_JNDI_FACTORY = "weblogic.jndi.WLInitialContextFactory";
    /**WLS_TX*/
    public static final String WLS_TX = "javax.transaction.UserTransaction";
    /**initialContext*/
    private static InitialContext initialContext = null;

    /**
     * @return
     * @throws NamingException
     */
    public InitialContext getInitialContext() throws NamingException {
        if (initialContext != null) {
            return initialContext;
        }
        if (local) {
            initialContext = new InitialContext();
        } else {
            Hashtable<String,String> env = new Hashtable<String,String>();
            env.put("java.naming.factory.initial", "weblogic.jndi.WLInitialContextFactory");
            env.put("java.naming.provider.url", url);
            env.put("java.naming.security.principal", userName);
            env.put("java.naming.security.credentials", password);

            initialContext = new InitialContext(env);
        }
        return initialContext;
    }

    /**
     * @param dsJNDIName
     * @return
     * @throws NamingException
     */
    public DataSource getDataSource(String dsJNDIName) throws NamingException{
        Context ctx = getInitialContext();
        return getDataSource(ctx, dsJNDIName);
    }

    /**
     * @return
     * @throws NamingException
     */
    public UserTransaction getUserTx() throws NamingException {
        Context ctx = getInitialContext();
        return getUserTx(ctx, "javax.transaction.UserTransaction");
    }

    /**
     * @return
     * @throws NamingException
     */
    public Context getEnvContext() throws NamingException {
        Context ctx = getInitialContext();
        return getEnvContext(ctx);
    }

}
